class Solution:
    def wordPattern(self, pattern: str, str: str) -> bool:
        p_list = list(pattern)
        s_list = str.split()
        mid_dict_p = {}
        mid_dict_s = {}
        if len(p_list) != len(s_list):
            return False
        for index, alpha in enumerate(p_list):
            if alpha not in mid_dict_p:
                mid_dict_p[alpha] = s_list[index]
            else:
                if mid_dict_p[alpha] != s_list[index]:
                    return False
            if s_list[index] not in mid_dict_s:
                mid_dict_s[s_list[index]] = alpha
            else:
                if mid_dict_s[s_list[index]] != alpha:
                    return False
        return True


a = Solution()
print(a.wordPattern(pattern="abba", str="dog cat cat dog"))
print(a.wordPattern(pattern = "abba", str = "dog cat cat fish"))
print(a.wordPattern(pattern = "aaaa", str = "dog cat cat dog"))
print(a.wordPattern(pattern = "abba", str = "dog dog dog dog"))
